import { Service } from 'egg';
const fs = require('fs');

/**
 * Test Service
 */
export default class user extends Service {

  /**
   * sayHi to you
   * @param name - your name
   */
  public async sayHi(name: string) {
    return `hi, ${name}`;
  }
  public async createUser({ username, password, scret_protection }) {
    let Users = await this.getUser(username);
    if (Users.length === 0) {
      const res1 = await this.ctx.model.User.create()
      console.log(res1.dataValues.id);
      const res2 = await this.ctx.model.Secret.create({
        user_id: res1.dataValues.id,
        username,
        password: this.ctx.helper.generatePwd(password),
        scret_protection
      })
      // console.log(res2);
      return res2.dataValues
    } else {
      throw new Error('错误');
    }
  }
  public async getUser(username: string, password?: string) {
    if (password) {
      let res = await this.ctx.model.Secret.findAll({
        where: {
          username,
          password: this.ctx.helper.generatePwd(password),
        }
      })
      if (res.length === 1) {
        let data = await this.ctx.model.User.findByPk(res[0].dataValues.user_id)
        return data.dataValues;
      } else {
        throw new Error('用户名密码错误！')
      }
    } else {
      let res = await this.ctx.model.Secret.findAll({
        where: {
          username
        }
      })
      // console.log(res);
      return res;
    }
  }
  public async changePassword(username: string, password: string, scret_protection?: string) {
    console.log(username, password, scret_protection);

    let res = await this.ctx.model.Secret.update({
      password: this.ctx.helper.generatePwd(password)
    }, {
      where: {
        username,
        scret_protection
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error()
    }

  }

  public async getPersonalInfo(req) {
    let res = await this.ctx.model.User.findOne({
      where: {
        id: req.user_id
      }
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }

  public async updatePassword(user_id: number, newPassword: string, oldPassword: string) {
    console.log(user_id, newPassword);
    let res1 = await this.ctx.model.Secret.findAll({
      where: {
        user_id,
        password:this.ctx.helper.generatePwd(oldPassword),
      }
    })
    if (res1.length === 1) {
      let res = await this.ctx.model.Secret.update({ password: this.ctx.helper.generatePwd(newPassword) }, {
        where: {
          user_id
        }
      })
      if (res[0] === 1) {
        return res
      } else {
        throw new Error('密码更改失败')
      }
    } else {
      throw new Error('密码错误')
    }

  }

  public async changePhoto() {
    const { ctx } = this
    const { image, user_id } = ctx.request.body;
    // const stream = await ctx.getFileStream(); // egg接收uni.uploadFile传递来的filePath会报错Invalid filename，
    // 因为egg为了安全设置白名单后缀，随机的filename无后缀，接收被拦截
    // const img = fs.readFileSync(files.image.path);

    const fileName = Date.now() + '.png';
    const time = ctx.helper.getNowFormatDate()

    const base64 = image.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64

    const path = 'app/public/uploads/' + time + '/' + fileName
    const store = 'public/uploads/' + time + '/' + fileName;
    const res = await ctx.model.User.update({
      photo: store
    }, {
      where: {
        id: user_id
      }
    })
    const dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象，
    const checkDir = fs.existsSync('app/public/uploads/' + time + '/'); // 判断目录是否存在
    if (!checkDir) {
      fs.mkdirSync('app/public/uploads/' + time + '/', { recursive: true }, (err) => { console.log(err); }) // 不存在则创建目录
    }
    fs.writeFile(path, dataBuffer, function (err) {//用fs写入文件
      if (err) {
        console.log(err);
      } else {
        console.log('写入成功！');
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error('更新失败')
    }
    // let paths = process.cwd()
    // // const storage = ctx.helper.random();
    // const checkDir = fs.existsSync(paths + '/app/public/uploads/' + time + '/'); // 判断目录是否存在
    // if (!checkDir) {
    //   fs.mkdir('app/public/uploads/' + time + '/', (err) => { console.log(err); }) // 不存在则创建目录
    // }
    // fs.writeFileSync('public/uploads/' + time + '/' + storage, img); // 将文件写入目录中
  }

  public async changeTelV(user_id: number, value: string) {

    let res = await this.ctx.model.User.update({ mobile: value }, {
      where: {
        id: user_id
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error()
    }

  }

  public async changeNameV(user_id: number, value: string) {

    let res = await this.ctx.model.User.update({ nick_name: value }, {
      where: {
        id: user_id
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error()
    }

  }

  public async changeGenderV(user_id: number, value: string) {

    let res = await this.ctx.model.User.update({ sex: value }, {
      where: {
        id: user_id
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error()
    }

  }

  public async changeSignV(user_id: number, value: string) {

    let res = await this.ctx.model.User.update({ sign: value }, {
      where: {
        id: user_id
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error()
    }

  }

  public async changeLocationV(user_id: number, value: string) {

    let res = await this.ctx.model.User.update({ address: value }, {
      where: {
        id: user_id
      }
    })
    if (res[0] === 1) {
      return res
    } else {
      throw new Error()
    }

  }

}
